package com.ruoyi.system.service.impl;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Coding makes me happy.
 * 　┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　☆☆☆　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┗━┓　史　┏━┛
 * 　　┃　诗　┃神兽保佑
 * 　　┃　之　┃代码无BUG！
 * 　　┃　宠　┗━━━┓
 * 　　┃Author:　　　┣┓
 * 　　┃　　  liu.Q　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 * ----------------------
 *
 * @Date : 上午11:18 2018/3/2
 * @Description :
 */
@Service
public class RedisService {
    @Resource
    private RedisTemplate redisTemplate;
    private static final String prefix = "";

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value) {
        key = prefix + key;
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean setExpire(String key, long expireTime, TimeUnit timeUnit) {
        return redisTemplate.expire(key, expireTime, timeUnit);
    }


    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value, Long expireTime, TimeUnit timeUnit) {
        key = prefix + key;
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(String key) {
        if (exists(key)) {
            key = prefix + key;
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(String key) {
        key = prefix + key;
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        key = prefix + key;
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     */
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     * @param len
     */
    public void lPush(String k, Object v, int len) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.leftPush(k, v);
        if (list.size(k) > len) {
            list.rightPop(k);
        }
    }

    /**
     * 列表获取
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    public Object rPop(String k) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.rightPop(k);
    }

    /**
     * 集合添加
     *
     * @param key
     * @param value
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     *
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 获得key数组里面key2元素的索引
     *
     * @param key
     * @param key2
     * @return
     */
    public Long rank(String key, Object key2) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rank(key, key2);
    }

    /**
     * 有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }

    /**
     * 获得key数组里面key2元素的排序值
     *
     * @param key
     * @param key2
     * @return
     */
    public double score(String key, Object key2) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.score(key, key2);
    }


    /**
     * 从高到低的排序集中获取从头(start)到尾(end)内的元素。
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<Object> reverseRange(String key, long start, long end) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.reverseRange(key, start, end);
    }

    /**
     * @Author : liu.q [916000612@qq.com]
     * @Time 2020/2/25 7:35 下午
     * @Description : 自增
     */
    public Long incr(String key) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        return increment;
    }

    /**
     * 获取当日流水号
     *
     * @return
     */
    public String getSerialNumber() {
        //时间戳 后面拼接流水号 如果需要  可以加上时分秒
        String datetime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //这里是 Redis key的前缀，如: sys:日期
        String key = MessageFormat.format("{0}:{1}", "sys", datetime);
        //查询 key 是否存在， 不存在返回 1 ，存在的话则自增加1
        long autoID = redisTemplate.opsForValue().increment(key, 1);
        // 设置key过期时间, 保证每天的流水号从1开始
        if (autoID == 1) {
            redisTemplate.expire(key, 1, TimeUnit.DAYS);
        }
        //这里是 2 位id，如果位数不够可以自行修改 ，下面的意思是 得到上面 key 的 值，位数为6 ，不够的话在左边补 0 ，比如  110 会变成  000110
        String value = StringUtils.leftPad(String.valueOf(autoID), 2, "0");
        //然后把 时间戳和优化后的 ID 拼接  格式 年月日6后五位流水号 例如 20210305600001
        return MessageFormat.format("{0}{1}{2}", datetime, value, RandomUtils.nextInt(10, 99));
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            int s = RandomUtils.nextInt(1, 99);
            System.out.println(s);
            System.out.println(StringUtils.leftPad(String.valueOf(s), 3, "0"));
        }
    }

    /**
     * 正则查询key
     *
     * @author liu.q[916000612@qq.com]
     * @time 2022/7/26 16:48
     */
    public Set<String> getKeys(String preKey) {
        Set keys = redisTemplate.keys(preKey + "*");
        return keys;
    }

    /**
     * @Time: 2021/5/9 21:40
     * @author: liu.q [916000612@qq.com]
     * @des: 批量删除
     */
    public Long dels(String preKey) {
        return redisTemplate.delete(getKeys(preKey));
    }


    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setnx(String key, Object value, Long expireTime, TimeUnit timeUnit) {
        key = prefix + key;
        boolean result = false;
        try {
            result = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, timeUnit);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


}
